package com.miracle.system.web;

import com.miracle.common.utils.SearchUtils;
import com.miracle.common.utils.SecurityUtils;
import com.miracle.common.utils.StringUtils;
import com.miracle.system.base.domain.ResultMap;
import com.miracle.system.domain.SysRole;
import com.miracle.system.service.SysRoleService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ：miracle.cui
 * @description：TODO
 * @date ：2020/8/11 13:56
 */
@ApiModel(value = "角色管理类")
@RestController
@RequestMapping("/system/role")
public class SysRoleController {

    @Autowired
    SysRoleService roleService;

    @ApiOperation(value = "角色列表")
    @GetMapping("/list")
    public ResultMap list(SysRole role){
        SearchUtils.startPage();
        List<SysRole> roleList = roleService.selectRoleList(role);
        return ResultMap.getPage(roleList);
    }

    @ApiOperation(value = "所有角色列表")
    @GetMapping("/all")
    public ResultMap all(SysRole role){
        List<SysRole> roleList = roleService.selectRoleList(role);
        return ResultMap.success(roleList);
    }

    /* 增 */
    @ApiOperation(value = "新增角色")
    @PostMapping
    public ResultMap add(@Validated @RequestBody SysRole role){

        role.setCreateBy(SecurityUtils.getUserId());
        Integer rows = roleService.insertRole(role);
        return rows > 0 ? ResultMap.success(role) : ResultMap.error();
    }

    /* 删 */
    @ApiOperation(value = "删除角色")
    @DeleteMapping
    public ResultMap delete(@Validated @RequestBody Integer[] roleIds){

        Integer rows = roleService.deleteRoleByRoleIds(roleIds);
        return rows > 0 ? ResultMap.success() : ResultMap.error();
    }

    /* 改 */
    @ApiOperation(value = "修改角色")
    @PutMapping
    public ResultMap edit(@Validated @RequestBody SysRole role){

        role.setLastUpdateBy(SecurityUtils.getUserId());
        Integer rows = roleService.updateRole(role);
        return rows > 0 ? ResultMap.success(role) : ResultMap.error();
    }

    /* 查 */
    @ApiOperation(value = "查询角色")
    @GetMapping(value = {"/", "/{roleId}"})
    public ResultMap getInfo(@PathVariable(value = "roleId", required = false) Integer roleId){

        if (StringUtils.isNotNull(roleId)){
            return ResultMap.success(roleService.selectRoleByRoleId(roleId));
        } else {
            return ResultMap.error();
        }
    }

    /* 远程校验 */
    @ApiOperation(value = "远程校验角色")
    @GetMapping(value = {"/remoteCheckRole"})
    public ResultMap remoteCheckRole(SysRole role){
        role.setStatus("enabled");
        SysRole checkRole = roleService.remoteCheckRole(role);
        return ResultMap.success(checkRole);
    }
}
